package com.imooc.retrofit;

import com.imooc.base.retrofit.Call;
import com.imooc.base.retrofit.Callback;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

public class OkHttpCall<T> implements Call<T> {

    final ServiceMethod serviceMethod;
    final Object[] args;

    public OkHttpCall(ServiceMethod serviceMethod, Object[] args) {
        this.serviceMethod = serviceMethod;
        this.args = args;
    }

    @Override
    public void enqueue(Callback<UserLoginResult> callback) {
        // 发起一个请求，给一个回调就完结了
        okhttp3.Call newCall = serviceMethod.createNewCall(args);
        newCall.enqueue(new okhttp3.Callback() {

            @Override
            public void onFailure(@NotNull okhttp3.Call call, @NotNull IOException e) {
                if (callback!=null){
                    callback.onFailure(OkHttpCall.this,e);
                }
            }
            @Override
            public void onResponse(@NotNull okhttp3.Call call, @NotNull okhttp3.Response response) throws IOException {
                Response rResponse = new Response();
                rResponse.body = serviceMethod.parseBody(response.body());

                if (callback!=null){
                    callback.onResponse(OkHttpCall.this,rResponse);
                }
            }
        });
    }
}
